﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using App.Models;
using App.Models.Pager;
using App.Views.ViewModels;
namespace App.Controllers
{
    public class RefriServiceController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult List(int? page, int? rows, string order)
        {
            dbe.ContextOptions.ProxyCreationEnabled = false;
            dbe.ContextOptions.LazyLoadingEnabled = false;

            int offset = (page ?? 1 - 1) * (rows ?? 10);
            PagedList<tb_RefriRecords> list = null;
            if ("asc" == order)
            {
                list = dbe.tb_RefriRecords.OrderBy(m => m.RefriNO)
                                .ToPagedList(page ?? 1, rows ?? 10);
            }
            else
            {
                list = dbe.tb_RefriRecords.OrderByDescending(m => m.RefriNO)
                                .ToPagedList(page ?? 1, rows ?? 10);
            }
            PagedList<RefriServiceEditViewModel> data = new PagedList<RefriServiceEditViewModel>(
                                                list.CurrentPageIndex, list.PageSize, list.total);
            data.rows.AddRange(from f in list.rows
                               select new RefriServiceEditViewModel
                               {
                                   RefriNO = f.RefriNO,
                                   ServiceNo = f.ServiceNo,
                                   DeadNO = dbe.tb_ServiceDetail.FirstOrDefault(m => m.ServiceNo == f.ServiceNo).DeadNO,
                                   CoffinNO = f.CoffinNO,
                                   EnterTime = f.EnterTime,
                                   ActualOutTime = f.ActualOutTime,
                                   EstimateOutTime = f.EstimateOutTime
                               });

            return Json(data, JsonRequestBehavior.AllowGet);
        }


        public ActionResult Create()
        {
            var vmodel = GetServiceItemList("", Utils.REFRI_SERVICE_TYPE);
            return PartialView("UCServicesItemList", vmodel);
        }

        [HttpPost]
        public ActionResult Create([Bind(Exclude = "ItemList")]RefriServiceEditViewModel vmodel)
        {
            try {
                //费用明细选择，通过页面的JS生成发下格式： id,qty,subtotal|id,qty,..
                string serviceNo = GenServiceNo();
                //保存在SelectedItemList属性中
                AddServiceItems(vmodel.DeadNO, serviceNo, vmodel.SelectedItemList);
                var model = new tb_RefriRecords
                {
                    RefriNO = GenRefriNO(),
                    ServiceNo = serviceNo,
                    CoffinNO = vmodel.CoffinNO,
                    EnterTime = vmodel.EnterTime,
                    EstimateOutTime = vmodel.EstimateOutTime,
                    ActualOutTime = vmodel.EstimateOutTime
                };
                dbe.tb_RefriRecords.AddObject(model);
                dbe.SaveChanges();
                CurrentDeader = vmodel.DeadNO;
                return Json(new { success = true }, JsonRequestBehavior.AllowGet);           
            }
            catch {
                return Json(new { success = false, msg = "添加出错！" }, JsonRequestBehavior.AllowGet);
            }                       
        }
        public ActionResult Edit(string id)
        {
            var model = dbe.tb_RefriRecords.FirstOrDefault(m => m.RefriNO == id);
            var vmodel = GetServiceItemList(model.ServiceNo, Utils.REFRI_SERVICE_TYPE);
            return PartialView("UCServicesItemList", vmodel);
        }
        
        [HttpPost]
        public ActionResult Edit(string id, RefriServiceEditViewModel vmodel)
        {
            try
            {
                //费用明细选择更新                                
                EditServiceItems(vmodel.SelectedItemList, vmodel.DeadNO, vmodel.ServiceNo);

                //保存冷藏信息
                var model = dbe.tb_RefriRecords.FirstOrDefault(m => m.RefriNO == id);
                model.CoffinNO = vmodel.CoffinNO;
                model.EnterTime = vmodel.EnterTime;
                model.EstimateOutTime = vmodel.EstimateOutTime;
                model.ActualOutTime = vmodel.EstimateOutTime;
                                
                dbe.SaveChanges();
                CurrentDeader = vmodel.DeadNO;
                return Json(new { success = true }, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                return Json(new { success = false, msg = "添加出错！" }, JsonRequestBehavior.AllowGet);
            }   
        }
        
        [HttpPost]
        public ActionResult Delete(string ids)
        {
            try
            {
                string[] idList = ids.Split('&');
                foreach (var id in idList)
                {
                    var obj = dbe.tb_RefriRecords.FirstOrDefault(m => m.RefriNO == id);
                    dbe.tb_RefriRecords.DeleteObject(obj);
                    //删除服务收费
                    DeleteServiceItems(obj.ServiceNo);
                }

                dbe.SaveChanges();
                var res = new { success = true };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
            catch
            {
                var res = new { success = false, msg = "删除出错！" };
                return Json(res, JsonRequestBehavior.AllowGet);
            }
        }
        
        public ActionResult SelectCoffin(string st, string et) {
            //禁止页面被缓存
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Today.AddYears(-2));  
                     
            var list = dbe.tb_RefriCoffinInfo.ToList();
            DateTime stime = DateTime.Now;
            DateTime etime = DateTime.Now;
            try
            {
                stime = DateTime.Parse(st);
                etime = DateTime.Parse(et);
            }
            catch { 
            
            }
            /*
            //暂时不考虑ActualOutTime，以EstimateOutTime为ActualOutTime，因此取消以下计算2011-08-21
            // m.ActualOutTime == null 表示该位置已经预约或在用 
            var useds = dbe.tb_RefriRecords.Where(m => m.ActualOutTime == null);
            var usedIdList = useds.Select(m => m.CoffinNO).ToList();
            var ulist = useds.ToList();
            //已经预约但在此段时间空间的
            var idles = useds.Where(m => m.EnterTime >= etime || m.EstimateOutTime <= stime);
            var idleIdList = idles.Select(m => m.CoffinNO).ToList();
            */
            //统计在EnterTime - EstimateOutTime 这个段时间已经预约或在用房间
            var useds = dbe.tb_RefriRecords.Where(m => m.EnterTime <= etime && m.EstimateOutTime > stime);
            var usedIdList = useds.Select(m => m.CoffinNO).ToList();
            var usedList = useds.ToList();
            List<RefriCoffinStatusViewModel> vlist = new List<RefriCoffinStatusViewModel>();   

            foreach (var c in list)
            {
                string status = "空闲";                
                string hintMsg = "";
                int pos = usedIdList.IndexOf(c.CoffinNO);
                if (pos >= 0)
                {
                    status = "在用";
                    hintMsg = string.Format("[{0:yyyy/MM/dd HH:mm}]-[{1:yyyy/MM/dd HH:mm}]", usedList[pos].EnterTime, usedList[pos].EstimateOutTime);                    
                }
                var lvi = new RefriCoffinStatusViewModel
                {
                    CoffinNO = c.CoffinNO,
                    CoffinName = c.CoffinModel,
                    Status = status,
                    Remark = hintMsg
                };                
                vlist.Add(lvi);
            }
            return PartialView(vlist);
        }
    }
}
